const XHS = {
    taskStep: 0,
    filePath: '',
    packName: 'com.xingin.xhs',
    AppPackName: "org.autojs.autojs",
    resourcePath: "/storage/emulated/0/dhs/resource/",
    sleepTime: '',
    taskTime: '',
    taskTimeSpace: 30000,
    swithcConfig: [
        { depth: 10, id: 'du6', desc: '首页' },
        { depth: 10, id: 'dua', desc: '热门' },
        { depth: 10, id: 'du9', desc: '发布' },
        { depth: 10, id: 'du8', desc: '消息' },
        { depth: 10, id: 'du7', desc: '我' },
    ],
    taskConfig: {
        // taskList:[],
        // taskStatus:false
    },
    ordinaryCode: {
        like_post: '1',
        save_post: '3',
        comment_post: '2',
        follow_user: '4'
    },
    CommentPage: 5,
    isTest: false,
    cacheTask: {
        task: {
            taskName: null,
            taskFunc: null,
            taskData: null,
        },
        taskId: null,
        cacheData: null
    },
    watchCache: false,
    taskThred: null,
    isHome: false,
    taskStart: false,
    getTaskList(taskInfo) {
        let taskList = []
        let { skey } = taskInfo
        switch (skey) {
            case 'reply_msg':
                taskList.push({
                    taskName: '回复消息(私信/赞和收藏/关注)',
                    taskFunc: replyMsgTask.start,
                    taskData: taskInfo
                })
                break;
            case 'rase_account':
                taskList.push({
                    taskName: '养号',
                    taskFunc: raseAccountTask.start,
                    taskData: taskInfo
                })
                break;
            case 'reply_comment':
                taskList.push({
                    taskName: '回复评论和@',
                    taskFunc: replyCommentTask.start,
                    taskData: taskInfo
                })
                break;
            case 'send_post':
                taskList.push({
                    taskName: '发笔记',
                    taskFunc: sendPostTask.start,
                    taskData: taskInfo
                })
                break;
            case 'get_user_data':
                taskList.push({
                    taskName: '统计博主数据',
                    taskFunc: getUserDataOrUserPostListTask.start,
                    taskData: taskInfo
                })
                break;
            case 'get_post_list_by_keyword':
                taskList.push({
                    taskName: '关键词采集笔记列表',
                    taskFunc: getPostByKeywordTask.start,
                    taskData: taskInfo
                })
                break;
            case 'get_post_comments_by_keyword':
                taskList.push({
                    taskName: '关键字采集评论用户',
                    taskFunc: getPostByKeywordTask.start,
                    taskData: taskInfo
                })
                break;
            case 'get_post_detail_by_link':
                taskList.push({
                    taskName: '链接采集笔记内容',
                    taskFunc: getPostByLinkTask.start,
                    taskData: taskInfo
                })
                break;
            case 'get_post_comments_by_link':
                taskList.push({
                    taskName: '链接采集评论用户',
                    taskFunc: getPostByLinkTask.start,
                    taskData: taskInfo
                })
                break;
            case 'get_post_list_by_user':
                taskList.push({
                    taskName: '红薯号采集笔记列表',
                    taskFunc: getUserDataOrUserPostListTask.start,
                    taskData: taskInfo
                })
                break;
            case 'get_post_comments_by_user':
                taskList.push({
                    taskName: '红薯号采集评论用户',
                    taskFunc: getCommentByUserTask.start,
                    taskData: taskInfo
                })
                break;
            case 'comment_post':
                taskList.push({
                    taskName: '评论笔记',
                    taskFunc: ordinaryTask.start,
                    taskData: taskInfo
                })
                break;
            case 'like_post':
                taskList.push({
                    taskName: '点赞笔记',
                    taskFunc: ordinaryTask.start,
                    taskData: taskInfo
                })
                break;
            case 'save_post':
                taskList.push({
                    taskName: '收藏笔记',
                    taskFunc: ordinaryTask.start,
                    taskData: taskInfo
                })
                break;
            case 'follow_user':
                taskList.push({
                    taskName: '关注用户',
                    taskFunc: ordinaryTask.start,
                    taskData: taskInfo
                })
                break;
            case 'at_user_in_post':
                taskList.push({
                    taskName: '评论区@用户',
                    taskFunc: attUserByLinkTask.start,
                    taskData: taskInfo
                })
                break;
            case 'handle_deal_msg':
                taskList.push({
                    taskName: '私信指定回复',
                    taskFunc: dealMsgTask.start,
                    taskData: taskInfo
                })
                break;
            default:
                break;
        }
        return taskList
    },
    errorTask(params) {
        //任务所有可执行功能全部报错
        console.log('提交报错任务:-----------：', params);
        // myUi.setTopText(params.taskData + ': ' + params.errorTip)
        //标记当前任务为错误任务状态
        XHS.taskConfig.nowTaskError = params
    },
    submitTaskStatus(nowTaskIndex, params) {
        //提交报错任务
        if (!params.task_data || params.task_data !== '没有任务配置参数，请检查') {
            let { taskList, nowTaskError } = XHS.taskConfig
            let taskinfo = taskList[nowTaskIndex].taskData
            let task_data = {}
            params['task_id'] = taskinfo.task_id
            params['task_status'] = nowTaskError ? 2 : 1
            switch (taskinfo.skey) {
                case 'rase_account':
                    task_data = raseAccountTask.raseAccountData
                    break;
                case 'send_post':
                    task_data = {
                        post_draft_id: taskinfo.setting.post_draft_id,
                        link: sendPostTask.taskConfig.sendLinke
                    }
                    break;
                case 'reply_comment':
                    task_data = replyCommentTask.replayUserList
                    break;
                case 'reply_msg':
                    task_data = replyMsgTask.replayUserList
                    break;
                case 'get_user_data':
                    task_data = getUserDataOrUserPostListTask.saveUserInfo
                    break;
                case 'get_post_list_by_user':
                    task_data = getUserDataOrUserPostListTask.saveUserInfo
                    break;
                case 'get_post_comments_by_link':
                    task_data = getPostByLinkTask.postList
                    break;
                case 'get_post_detail_by_link':
                    task_data = getPostByLinkTask.postList
                    break;
                case 'get_post_comments_by_user':
                    task_data = getCommentByUserTask.savePostInfo
                    break;
                case 'get_post_comments_by_keyword':
                    task_data = getPostByKeywordTask.postList
                    break;
                case 'get_post_list_by_keyword':
                    task_data = getPostByKeywordTask.postList
                    break;
                case 'at_user_in_post':
                    task_data = ''
                    break;
                case 'handle_deal_msg':
                    task_data = ''
                    break;
                default:
                    let taskIdList = taskinfo.setting.batch_keyword
                    task_data = {
                        batch_id: taskinfo.setting.batch_id,
                        batch_type: XHS.ordinaryCode[taskinfo.skey],
                        finish_num: ordinaryTask.taskConfig.errorTask == 999 ? 0 : taskIdList.length - ordinaryTask.taskConfig.errorTask * 1
                    }
                    break;
            }
            sleep(1000)
            params['task_data'] = task_data ? JSON.stringify(task_data) : ''
            if(nowTaskError.errorTip){
                params['task_data'] = nowTaskError.errorTip
            }
        }
        // 上传参数汇总
        console.log('上传参数汇总:-----------：\n', params);
        Api.doneData(params, (res) => {
            console.log('res' + JSON.stringify(res));
            //提取缓存状态
            if (XHS.watchCache && XHS.cacheTask.task.taskData) {
                console.log('提取缓存状态');
                //模拟任务接口获取任务
                XHS.isHome = true
                XHS.openApp(XHS.cacheTask.task.taskData)
                return
            }
            myUi.setTopText(Comman.getDate() + ': ' + "任务上报完成，正在等待更新任务...")
            XHS.isHome = false
            //正常状态 休息一分钟后请求任务接口，防止频繁请求接口导致被封禁
            home()
            sleep(60000)
            XHS.getXhsTask()
        })
    },
    watchValue(key, newVal) {
        let { taskList, nowTaskIndex } = XHS.taskConfig
        switch (key) {
            case 'taskStatus':
                //任务执行完成，更新执行下一条任务
                if (newVal) {
                    try {
                        myUi.setTopText(Comman.getDate() + ': ' + taskList[nowTaskIndex].taskName + "已执行完成")
                    } catch (error) {
                        console.log(error);
                    }
                    XHS.taskConfig.nowTaskIndex += 1
                }
                break;
            case 'nowTaskIndex':
                let homeMnue = btnConfig.home.homeMnue
                let num = 0
                sleep(1000)
                //重置首页
                while (!depth(homeMnue.options.depth).id(homeMnue.options.id).exists()) {
                    back();
                    console.log('back...');
                    sleep(1000)
                    if (num >= 10) {
                        myUi.setTopText(Comman.getDate() + ': ' + "小红书启动异常，尝试启动到软件首页...")
                        App.launchApp(XHS.packName);
                    }
                    // if (num >= 15) {
                    //     myUi.setTopText(Comman.getDate() + ': ' + "小红书启动异常，请重启脚本软件...")
                    // }

                    num += 1
                    sleep(1000);
                }
                if (newVal < taskList.length) {
                    myUi.setTopText(Comman.getDate() + ': ' + "开始执行：" + taskList[newVal].taskName + "任务...")
                    let params = taskList[newVal].taskData
                    sleep(1000)

                    if (!params.setting && params.task_id) {
                        XHS.taskConfig.nowTaskError = ''
                        console.log('当前获取任务存在异常')
                        myUi.setTopText(Comman.getDate() + ': ' + "任务：" + taskList[newVal].taskName + "配置参数异常，正在反馈并更新任务队列...")
                        XHS.submitTaskStatus(0, { task_data: '没有任务配置参数，请检查', task_id: params.task_id, task_status: 2 })
                        return
                    }

                    try {
                        //开启新线程执行任务
                        XHS.taskThred = threads.start(
                            function () {
                                taskList[newVal].taskFunc(params)
                            }
                        )

                    } catch (error) {
                        console.log('当前任务执行异常,error: ' + error);
                        XHS.errorTask(
                            {
                                taskType: params.skey,
                                taskName: taskList[newVal].taskName,
                                taskData: 'error',
                                taskDate: Comman.getDate()
                            }
                        )
                        //手动更新当前任务
                        XHS.taskConfig.taskStatus = true
                    }
                } else {
                    // myUi.setTopText(Comman.getDate() + ': ' + taskList[0].taskName + "任务已执行完成...")
                    //提交当前任务状态
                    XHS.submitTaskStatus(0, {})
                }
                break;
            default:
                break;
        }
    },
    init() {
        XHS.taskStart = true
        //打开小红书
        let openFlage = App.launchApp(XHS.packName);
        if (!openFlage) {
            myUi.setTopText(Comman.getDate() + ': ' + "打开小红书失败，请手动打开...")
            return
        }
        myUi.setTopText(Comman.getDate() + ': ' + "脚本初始化中...")
        sleep(1000)

        let homeMnue = btnConfig.home.homeMnue
        //重置首页
        while (!depth(homeMnue.options.depth).id(homeMnue.options.id).exists()) {
            myUi.setTopText(Comman.getDate() + ': ' + "尝试自动启动到软件首页...")
            launch(XHS.packName)
            sleep(2000);
            back()
            sleep(1000);
        }
        //打开个人中心
        App.openBtn(4)
        sleep(2000)
        if (!XHS.isTest) {
            myUi.setTopText(Comman.getDate() + ': ' + "系统校验关联小红书账户中...")
            console.log('小红书号为' + myUi.deviceInfo.xhsid)
            let xhsIdDom = id('gxr').textContains(myUi.deviceInfo.xhsid).findOne(3000)
            if (!xhsIdDom) {
                confirm('账户关联不通过，请登录设备绑定的小红书号后重启脚本')
                return
            }
        }
        XHS.getXhsTask()
    },
    getXhsTask() {
        //脚本已被用户关闭
        if (!XHS.taskStart) {
            return
        }
        let cacheId = XHS.cacheTask.taskId || ''
        let taskList = XHS.taskConfig.taskList

        if (!XHS.watchCache) {
            myUi.setTopText(Comman.getDate() + ': ' + "任务更新中...")
        }
        if (XHS.taskThred) {
            console.log('xhs.taskThred', XHS.taskThred.isAlive());
        }
        console.log('cacheId：', cacheId);
        Api.getTask({}, (res) => {
            //无委派任务 或者 养号任务执行中且当前任务和养号一致，开启自动更新任务
            if (!res.skey || (res.skey && res.task_id == cacheId)) {
                if (!XHS.isHome) {
                    //回首页，避免小红书软件长时间停留
                    XHS.isHome = true
                    home()
                }
                //开启自动更新任务
                setTimeout(() => {
                    XHS.getXhsTask()
                }, XHS.taskTimeSpace);

            } else {
                // 开启缓存监听后满足新任务条件 - 缓存任务状态
                if (XHS.watchCache && taskList.length && !XHS.taskConfig.taskStatus) {
                    XHS.nowTaskCache()
                }
                //执行新任务，首页标记去除
                XHS.openApp(res)
            }
        })
    },
    nowTaskCache() {
        let { taskList, nowTaskIndex } = XHS.taskConfig
        console.log('\n 缓存用户任务状态... \n');
        console.log(JSON.stringify(
            {
                task: taskList[nowTaskIndex],
                taskId: taskList[nowTaskIndex].taskData.taskId,
                cacheData: raseAccountTask.raseAccountData
            }
        ))
        console.log('\n');
        if (XHS.taskThred.isAlive()) {
            XHS.taskThred.interrupt()
        }
        XHS.cacheTask = {
            task: taskList[nowTaskIndex],
            taskId: taskList[nowTaskIndex].taskData.taskId,
            cacheData: raseAccountTask.raseAccountData
        }
    },
    clearTask() {
        if (XHS.taskThred && XHS.taskThred.isAlive()) {
            XHS.taskThred.interrupt()
        } else {
            log('当前任务已结束，无需清除')
        }
        XHS.taskStart = false
    },
    openApp(params) {
        let openFlage = App.launchApp(XHS.packName);
        if (!openFlage) {
            myUi.setTopText(Comman.getDate() + ': ' + "打开小红书失败，请手动打开...")
            return
        }
        XHS.isHome = false
        sleep(1000)
        if (params) {
            //传入参数,初始化任务配置项
            let taskList = XHS.getTaskList(params)
            let nowTaskConfig = {
                taskList: taskList,
                taskStatus: false,
                nowTaskIndex: 0,
                runTaskNum: 0,
                nowTaskError: ''
            }
            XHS.taskConfig = Comman.defineReactive(
                nowTaskConfig,
                '',
                XHS.watchValue
            )
            sleep(2000)
            XHS.taskConfig.nowTaskIndex = 0
        }
    }
};
module.exports = XHS